﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using iemtm.WeChat.Core.Consts;
using Mapster;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace iemtm.WeChat.Core.Managers
{
    public class WorkManager : IWorkManager, IScoped
    {
        private readonly IRepository<UserAccount> _userAccountRepository;
        private readonly IMemoryCache _memoryCache;
        public WorkManager(IRepository<UserAccount> userAccountRepository,IMemoryCache memoryCache)
        {
            _userAccountRepository = userAccountRepository;
            _memoryCache = memoryCache;
        }
        public int UserId { get => int.Parse(App.User?.FindFirstValue("UserId")); }

        public UserAccount CurrentUser
        {
            get
            {
                
                    return _memoryCache.GetOrCreate(string.Format(MemoryCacheConsts.CurrentUserInfo, UserId), entry =>
                    {
                        string gerUserSql = @"select ua.*,r.RoleName,c.CompanyName,a.AreaCode,a.AreaName,p.PrjName from UserAccount ua
                            left Join [Role] r on r.RoleCode=ua.RoleCode
                            left Join Company c on c.CompanyCode=ua.CompanyCode
                            left Join Area a on a.AreaCode=c.AreaCode
                            left Join Project p on p.PrjCode=ua.PrjCode
                             where ua.Id=@Id";
                        var userInfos = gerUserSql.SqlQuery<UserAccount>(new { Id = UserId });
                        if (userInfos != null && userInfos.Count > 0)
                        {
                            string Perurl = "SELECT a.MenuCode,b.URL FROM dbo.Permission a LEFT JOIN dbo.MenuItem b ON b.MenuCode = a.MenuCode WHERE a.RoleCode=@RoleCode";
                            var dtPer = Perurl.SqlQuery(new { RoleCode = userInfos[0].RoleCode });
                            if (dtPer != null && dtPer.Rows.Count > 0)
                            {
                                userInfos[0].PerCodes = (from t in dtPer.AsEnumerable() select t.Field<string>("MenuCode")).ToList();
                                userInfos[0].PerUrls = (from t in dtPer.AsEnumerable() select t.Field<string>("URL")).ToList();
                            }
                            else
                            {
                                userInfos[0].PerCodes = new List<string>();
                                userInfos[0].PerUrls = new List<string>();
                            }
                            return userInfos[0];
                        }
                        else
                        {
                            return null;
                        }
                    });              
            }
        }

    }
}
